package com.smartfast4j.springboot.redis.demo;

import com.smartfast4j.springboot.redis.demo.message.Receiver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import java.util.concurrent.CountDownLatch;

@SpringBootApplication
public class SpringbootRedisApplication {

	private static final Logger LOGGER = LoggerFactory.getLogger(SpringbootRedisApplication.class);

	/**
	 * 注入消息监听容器
	 * @param connectionFactory
	 * @param listenerAdapter
	 * @return
	 */
	@Bean
	RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
											MessageListenerAdapter listenerAdapter) {

		RedisMessageListenerContainer container = new RedisMessageListenerContainer();
		container.setConnectionFactory(connectionFactory);
		//接收从chat和gacl这两个通道发送过来的消息
		container.addMessageListener(listenerAdapter, new PatternTopic("chat"));
		container.addMessageListener(listenerAdapter, new PatternTopic("gacl"));

		return container;
	}

	@Bean
	MessageListenerAdapter listenerAdapter(Receiver receiver) {
		return new MessageListenerAdapter(receiver, "receiveMessage");
	}

	@Bean
	Receiver receiver(CountDownLatch latch) {
		return new Receiver(latch);
	}

	@Bean
	CountDownLatch latch() {
		return new CountDownLatch(1);
	}

	public static void main(String[] args) throws InterruptedException {
		SpringApplication.run(SpringbootRedisApplication.class, args);
	}
}
